import store from 'src/store'
import queryString from 'qs'
import axios from 'axios'
import config from 'src/config'
let _self = window

// 安装
export const setup = async ({commit}, callback) => {
  // 加载角色数据
  const parsed = queryString.parse(window.location.search.replace(/(\\?)*./, ''))
  let token = parsed.session_token || _self.$cache.get('session_token')
  if (token) {
    store.dispatch('profile', token)
  }
  // 加载微信设置
  await store.dispatch('loadWechat')
  // 初始化数据
  await store.dispatch('init')
  callback()
}

// 加载微信
export const loadWechat = async ({commit}) => {
  const local = window.location.href.split('#')[0]
  const url = config['urls']['wx_jsapi_config']
  const result = await axios.get(url, {
    params: {path: local}
  })
  window.wx.config(result.data)
}

// 初始化数据
export const init = async ({commit}) => {
  await store.dispatch('loadScroll') // 加载滚动图片
  await store.dispatch('loadActivity') // 加载活动列表
  await store.dispatch('loadProduct') // 加载产品
}

// 加载个人数据
export const profile = async ({commit}, token) => {
  _self.$cache.set('session_token', token, {exp: 60 * 60 * 24})
  store.dispatch('reloadProfile')
}

// 重新加载个人数据
export const reloadProfile = async ({commit}) => {
  let result = await _self.$rpc.invoke('user_profile', []).complete()
  if (result.code === 0) {
    commit('INIT_PROFILE', result.data)
    console.log('profile', JSON.parse(JSON.stringify(result.data)))
    store.dispatch('loadCart')
  }
}

// 登录处理
export const login = async ({commit}, {username, password}) => {
  let result = await _self.$rpc.invoke('user_login', [
    username,
    password
  ]).complete()
  if (result.code === 0) {
    store.dispatch('profile', result.data.token)
  }
  return result
}

// 登出处理
export const logout = async ({commit}) => {
  let result = await _self.$rpc.invoke('user_logout', []).complete()
  if (result.code === 0) {
    _self.$cache.delete('session_token')
    commit('INIT_PROFILE', null)
    store.dispatch('loadCart')
  }
  return result
}

// 获得页面内容
export const getPager = async ({commit}, name) => {

}

// 加载滚动图片
export const loadScroll = async ({commit}, type = 1) => {
  let result = await _self.$rpc.invoke('scrollimg_lists', [type]).complete()
  if (result.code === 0) {
    commit('LOAD_BANNER', result.data)
  }
}

// 加载活动列表
export const loadActivity = async ({commit}) => {
  let result = await _self.$rpc.invoke('activity_lists').complete()
  if (result.code === 0) {
    commit('LOAD_ACTIVITY', result.data)
  }
}

// 加载产品
export const loadProduct = async ({commit}) => {
  const result = await _self.$rpc.invoke('product_lists').complete()
  if (result.code === 0) {
    commit('LOAD_PRODUCT', result.data)
  }
}

// 加载购物车
export const loadCart = async ({commit}) => {
  let uuid = store.getters.getProfile ? store.getters.getProfile.uuid : ''
  let cartProduct = _self.$cache.get('cart_' + uuid) || []
  if (uuid && cartProduct.length < 1) {
    cartProduct = _self.$cache.get('cart_') || []
    _self.$cache.set('cart_' + uuid, cartProduct)
  }
  commit('LOAD_CART', cartProduct)
}

// 注册用户
export const registry = async ({commit}, {role, username, password, phone, fullname}) => {
  let result = await _self.$rpc.invoke('user_register', [role, username, password, phone, fullname]).complete()
  if (result.code === 0) {
    await store.dispatch('login', {username, password})
  }
  return result
}

// 添加购物车
export const addCart = async ({commit}, {id, model, order}) => {
  let uuid = store.getters.getProfile ? store.getters.getProfile.uuid : ''
  let cart = _self.$cache.get('cart_' + uuid) || []
  let bool = false
  for (let item of cart) {
    if (item && item.id === id) {
      item.order.count = (item.order.count || 0) + 1
      item.checked = true
      bool = true
      break
    }
  }
  if (!bool && model && order) {
    cart.push({id, model, order, checked: true})
  }
  _self.$cache.set('cart_' + uuid, cart)
  commit('LOAD_CART', cart)
}
// 减去购物车量
export const minusCart = async ({commit}, {id}) => {
  let uuid = store.getters.getProfile ? store.getters.getProfile.uuid : ''
  let cart = _self.$cache.get('cart_' + uuid) || []
  for (let item of cart) {
    if (item && item.id === id) {
      item.order.count = item.order.count > 0 ? item.order.count - 1 : 0
      if (!item.order.count && item.checked) {
        item.checked = false
      }
      break
    }
  }
  _self.$cache.set('cart_' + uuid, cart)
  commit('LOAD_CART', cart)
}
// 切换选择购物车
export const toggleCart = async ({commit}, {id}) => {
  let uuid = store.getters.getProfile ? store.getters.getProfile.uuid : ''
  let cart = _self.$cache.get('cart_' + uuid) || []
  for (let item of cart) {
    if (item && item.id === id) {
      item.checked = !item.checked
      break
    }
  }
  _self.$cache.set('cart_' + uuid, cart)
  commit('LOAD_CART', cart)
}
// 删除购物车商品
export const removeCart = async ({commit}, {id}) => {
  let uuid = store.getters.getProfile ? store.getters.getProfile.uuid : ''
  let cart = _self.$cache.get('cart_' + uuid) || []
  let index = -1
  for (let i in cart) {
    let item = cart[i]
    if (item && item.id === id) {
      index = i
      break
    }
  }
  if (index > -1) {
    cart.splice(index, 1)
  }
  _self.$cache.set('cart_' + uuid, cart)
  commit('LOAD_CART', cart)
}
// 清空购物车商品
export const clearCart = async ({commit}) => {
  let uuid = store.getters.getProfile ? store.getters.getProfile.uuid : ''
  let cart = []
  _self.$cache.set('cart_' + uuid, cart)
  commit('LOAD_CART', cart)
}
